<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
  <title>选择地址</title>


  <style type="text/css">
    body, html {
      width: 100%;
      height: 100%;
      margin: 0;
      font-family: "微软雅黑";
    }

    #mapDiv {
      height: 50%;
      width: 100%;
    }

    input, p {
      margin-top: 10px;
      margin-left: 5px;
      font-size: 14px;
    }
    .btn {
      display: block;
      padding: 5px;
      background-color: #75797d;
      border: 0;
      color: #ffffff;
      height: 40px;
      width: 50%;
    }
    .btn-list {
      display:flex;
      justify-content: space-between;
    }

  </style>


</head>
<body onLoad="onLoad()">
<div class="btn-list" >
  <button class="btn" type="button" id="back">返回</button>
  <button class="btn" type="button" id="sure">选择</button>

</div>
<div id="ton"></div>
<div id="mapDiv"></div>
<p>本例演示设置途经点进行驾车换乘查询</p>
<div id="driving_way">
</div>

<script type="text/javascript">
  var userAgent = navigator.userAgent;
  if (userAgent.indexOf('AlipayClient') > -1) {
    // 支付宝小程序的 JS-SDK 防止 404 需要动态加载，如果不需要兼容支付宝小程序，则无需引用此 JS 文件。
    document.writeln('<script src="https://appx/web-view.min.js"' + '>' + '<' + '/' + 'script>');
  } else if (/QQ/i.test(userAgent) && /miniProgram/i.test(userAgent)) {
    // QQ 小程序
    document.write(
      '<script type="text/javascript" src="https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"><\/script>'
    );
  } else if (/miniProgram/i.test(userAgent) && /micromessenger/i.test(userAgent)) {
    // 微信小程序 JS-SDK 如果不需要兼容微信小程序，则无需引用此 JS 文件。
    document.write('<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"><\/script>');
  } else if (/toutiaomicroapp/i.test(userAgent)) {
    // 头条小程序 JS-SDK 如果不需要兼容头条小程序，则无需引用此 JS 文件。
    document.write(
      '<script type="text/javascript" src="https://s3.pstatp.com/toutiao/tmajssdk/jssdk-1.0.1.js"><\/script>');
  } else if (/swan/i.test(userAgent)) {
    // 百度小程序 JS-SDK 如果不需要兼容百度小程序，则无需引用此 JS 文件。
    document.write(
      '<script type="text/javascript" src="https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.18.js"><\/script>'
    );
  } else if (/quickapp/i.test(userAgent)) {
    // quickapp
    document.write('<script type="text/javascript" src="https://quickapp/jssdk.webview.min.js"><\/script>');
  }
  // if (!/toutiaomicroapp/i.test(userAgent)) {
  //   document.querySelector('.post-message-section').style.visibility = 'visible';
  // }
</script>
<!--<script type="text/javascript" src="https://api.tianditu.gov.cn/api?v=4.0&tk=ca0f6a193803471f59c909e5768c8860"></script>-->
<script src="./tdt.api.4.0.0.js"></script>
<script type="text/javascript" src="./uni.webview.1.5.4.js"></script>
<script type="text/javascript">
  // 绑定hashchange
  // window.addEventListener('hashchange', ()=>{
  //   console.log("触发hashchange"+window.location.href);
  // });

  //在webview中添加代码
  let hash;
  // 监听hash变化
  window.addEventListener("hashchange", function() {
    // 有hash值时返回上一个页面，并储存hash。
    // 因为返回了上一个页面，会立马进入else分支。
    // 将存好的hash渲染到页面
    if(location.hash){
      hash = location.hash.split('#')[1];
      history.back();
    } else {
      //hash值最好是编码后的数据
      document.getElementById('ton').innerHTML = '解码后参数：' + decodeURIComponent(hash);
    }
  }, false);

  document.addEventListener('UniAppJSBridgeReady', function() {

    uni.postMessage({
      data: {
        action: '测试message'
      }
    });
    uni.getEnv(function (res) {
      console.log('当前环境：' + JSON.stringify(res));
    });
    document.getElementById('back').addEventListener('click', function() {
      uni.navigateBack({
        action: 'back',
        delta: 1
      });

        var messageData = {
          content: '这是从H5页面中发送的消息'
        }

        var sendData = JSON.stringify(messageData)
        //window.parent.postMessage(sendData, '*')


    });
    document.getElementById('sure').addEventListener('click', function() {
      uni.postMessage({
        data: {
          action: 'sure'
        }
      });
    });
  });

  let map;
  const zoom = 16;
  let lon;
  let lat;
  var drivingRoute;
  var startIcon = "http://lbs.tianditu.gov.cn/images/bus/start.png";  //起点图标
  var endIcon = "http://lbs.tianditu.gov.cn/images/bus/end.png";      //终点图标
  var mid = "http://lbs.tianditu.gov.cn/images/driving/routeWayPoint.png";
  var startLngLat;
  var endLngLat;
  var mid1;
  var mid2;
  var infoWin = null;
  //取url中的参数值
  function getQuery(name) {
    // 正则：[找寻'&' + 'url参数名字' = '值' + '&']（'&'可以不存在）
    let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    let r = window.location.search.substr(1).match(reg);
    console.log(r);
    if(r != null) {
      // 对参数值进行解码
      return decodeURIComponent(r[2]);
    }
    return null;
  }
  function addMapClick()
  {
    removeMapClick();
    map.addEventListener("click",MapClick);
  }

  function removeMapClick()
  {
    map.removeEventListener("click",MapClick);
  }

  function MapClick(e)
  {
    map.clearOverLays();
    var marker = new T.Marker(new T.LngLat(e.lnglat.getLng(), e.lnglat.getLat()));
    //向地图上添加标注
    map.addOverLay(marker);
    // alert(e.lnglat.getLng()+","+e.lnglat.getLat());
    lon = e.lnglat.getLng();
    lat = e.lnglat.getLat();
  }


  function onLoad() {
    map = new T.Map('mapDiv');
    map.centerAndZoom(new T.LngLat(123.373200,41.801260), zoom);


    var config = {
                pageCapacity: 10,	//每页显示的数量
                onSearchComplete: localSearchResult	//接收数据的回调函数
            };
            //创建搜索对象
    var localsearch = new T.LocalSearch(map, config);
    localsearch.search("");
    // const config = {
    //   policy: 0,  //驾车策略
    //   onSearchComplete: searchResult  //检索完成后的回调函数
    // };
    // console.log(map);
    // drivingRoute = new T.DrivingRoute(map, config);
    // console.log(drivingRoute);
    // searchDrivingRoute()
  }

  function searchDrivingRoute() {
    map.clearOverLays();
    startLngLat = new T.LngLat(116.267620, 39.800100);
    endLngLat = new T.LngLat(116.608890, 40.026560);
    mid1 = new T.LngLat(116.306080, 39.960810);
    mid2 = new T.LngLat(116.455420, 39.874440);
    //驾车路线搜索
    drivingRoute.search(startLngLat, endLngLat, [mid1, mid2])
  }

  function createRoute(lnglats, lineColor) {
    //创建线对象
    var line = new T.Polyline(lnglats, {color: "#2C64A7", weight: 5, opacity: 0.9});
    //向地图上添加线
    map.addOverLay(line);
  }

  //添加起始点
  function createStartMarker(result) {
    var startMarker = new T.Marker(result.getStart(), {
      icon: new T.Icon({
        iconUrl: startIcon,
        iconSize: new T.Point(44, 34),
        iconAnchor: new T.Point(12, 31)
      })
    });
    map.addOverLay(startMarker);
    var endMarker = new T.Marker(result.getEnd(), {
      icon: new T.Icon({
        iconUrl: endIcon,
        iconSize: new T.Point(44, 34),
        iconAnchor: new T.Point(12, 31)
      })
    });
    map.addOverLay(endMarker);
    var midMarker1 = new T.Marker(mid1, {
      icon: new T.Icon({
        iconUrl: mid,
        iconSize: new T.Point(22, 23),
        iconAnchor: new T.Point(12, 23)
      })
    });
    map.addOverLay(midMarker1);
    var midMarker2 = new T.Marker(mid2, {
      icon: new T.Icon({
        iconUrl: mid,
        iconSize: new T.Point(22, 23),
        iconAnchor: new T.Point(12, 23)
      })
    });
    map.addOverLay(midMarker2);
  }

  function searchResult(result) {
    console.log(result);
    //添加起始点
    createStartMarker(result);

    obj = result;
    var resultList = document.createElement("div");
    //获取方案个数
    var routes = result.getNumPlans();
    for (var i = 0; i < routes; i++) {

      //获得单条驾车方案结果对象
      var plan = result.getPlan(i);

      //显示单个方案面板
      var div = document.createElement("div");
      div.style.cssText = "font-size:12px; cursor:pointer; border:1px solid #999999";

      //显示方案内容
      var describeStr = "<strong>总时间：" + plan.getDuration() + "秒，总距离：" + Math.round(plan.getDistance()) + "公里</strong>";
      describeStr += "<div><img src='" + startIcon + "'/>" + "116.267620,39.800100" + "</div>";

      //显示该方案每段的描述信息
      var numRoutes = plan.getNumRoutes();
      for (var m = 0; m < numRoutes; m++) {
        var route = plan.getRoute(m);
        describeStr += (m + 1) + ".<span>" + route.getDescription() + "</span><br/>"

        //显示该方案每段的详细描述信息
        var numStepsStr = "";
        var numSteps = route.getNumSteps();
        for (var n = 0; n < numSteps; n++) {
          var step = route.getStep(n);
          numStepsStr += "<p>" + (n + 1) + ")<a href='javascript://' onclick='showPosition(\"" + step.getPosition().getLng() + "\",\"" + step.getPosition().getLat() + "\",\"" + step.getDescription() + "\");'>" + step.getDescription() + "</a></p>";
        }
        describeStr += numStepsStr;
      }
      describeStr += "<div><img src='" + endIcon + "'/>" + "116.608890,40.026560" + "</div>";
      div.innerHTML = describeStr;
      resultList.appendChild(div);

      //显示驾车线路
      createRoute(plan.getPath());
      //显示最佳级别
      map.setViewport(plan.getPath());
    }
    //显示公交搜索结果
    document.getElementById("driving_way").appendChild(resultList);
  }

  //定位关键点
  function showPosition(lng, lat, des) {
    if (infoWin) {
      map.removeOverLay(infoWin);
      infoWin = null;
    }
    var lnglat = new T.LngLat(lng, lat);
    infoWin = new T.InfoWindow(des, new T.Point([0, 0]));
    infoWin.setLngLat(lnglat);
    map.addOverLay(infoWin);
  }

</script>


</body>
</html>
